package Perlbal::Plugin::Regex;

use strict;
use warnings;
no  warnings qw(deprecated);

our %Services;  # service_name => $svc

# when "LOAD" directive loads us up
sub load {
    my $class = shift;

    Perlbal::register_global_hook('manage_command.regex', sub {
        my $mc = shift->parse(qr/^regex\s+(?:(\w+)\s+)?(\S+)\s+(\S+)\s*=\s*(\w+)$/,
                              "usage: REGEX [<service>] <host_or_pattern> <regex> = <dest_service>");
        my ($selname, $host, $regex, $target) = $mc->args;
        unless ($selname ||= $mc->{ctx}{last_created}) {
            return $mc->err("omitted service name not implied from context");
        }

        my $ss = Perlbal->service($selname);
        return $mc->err("Service '$selname' is not a selector service")
            unless $ss && $ss->{role} eq "selector";

        $host = lc $host;
        return $mc->err("invalid host pattern: '$host'")
            unless $host =~ /^[\w\-\_\.\*\;\:]+$/;

        $ss->{extra_config}->{_regex} ||= {};
        $ss->{extra_config}->{_regex}{$host}->{regex}  = $target;
        $ss->{extra_config}->{_regex}{$host}->{target} = $target;

        return $mc->ok;
    });
    return 1;
}
# unload our global commands, clear our service object
sub unload {
    my $class = shift;

    Perlbal::unregister_global_hook('manage_command.regex');
    unregister($class, $_) foreach (values %Services);
    return 1;
}

# called when we're being added to a service
sub register {
    my ($class, $svc) = @_;
    unless ($svc && $svc->{role} eq "selector") {
        die "You can't load the regex plugin on a service not of role selector.\n";
    }

    $svc->selector(\&regex_selector);
    $svc->{extra_config}->{_regex} = {};

    $Services{"$svc"} = $svc;
    return 1;
}

# called when we're no longer active on a service
sub unregister {
    my ($class, $svc) = @_;
    $svc->selector(undef);
    delete $Services{"$svc"};
    return 1;
}
# call back from Service via ClientHTTPBase's event_read calling service->select_new_service(Perlbal::ClientHTTPBase)
sub regex_selector {
    my Perlbal::ClientHTTPBase $cb = shift;

    my $req = $cb->{req_headers};
    return $cb->_simple_response(404, "Not Found (no reqheaders)") unless $req;

    my $vhost = $req->header("Host");
    my $uri = $req->request_uri;
    my $maps = $cb->{service}{extra_config}{_regex} ||= {};

    $vhost =~ s/:\d+$//;

    my $regex  = $maps->{$vhost}->{regex}  ||= '';
    my $target = $maps->{$vhost}->{target} ||= '';

    if ($regex && $target) {
        my $svc = Perlbal->service($target) || undef;

        unless ($svc) {
            $cb->_simple_response(404, "Not Found (no configured regex)");
        } else {
            $svc->adopt_base_client($cb);
        }
    }
}

1;
